package com.sxf.util;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JSONUtils {

	/**
	 * Generate JSON to JSONP
	 * 
	 * @param callbackName
	 * @param jsonValue
	 *            json
	 * @return
	 */
	public static String writeValueAsJSONP(String callbackName, String jsonValue) {
		String returnVal = jsonValue;
		if (callbackName != null && !"".equals(callbackName.trim())) {
			returnVal = callbackName + "(" + jsonValue + ")";
		}
		return returnVal;
	}

	/**
	 * 输出可以为json或者jsonp <br>
	 * 用jsonp时browse必须要带回包含callback字段的参数名
	 * 
	 * @param request
	 * @param response
	 * @param jsonValue
	 * @throws Exception
	 */

	@SuppressWarnings("unchecked")
	public static void writeJSONP(HttpServletRequest request,
			HttpServletResponse response, String jsonValue) throws Exception {
		String callbackName = null;
		Map<String, String[]> parametMap = request.getParameterMap();
		if (parametMap != null && !parametMap.isEmpty()) {
			for (Iterator<String> it = parametMap.keySet().iterator(); it
					.hasNext();) {
				String obj = it.next();
				if (obj.toLowerCase().contains("callback")) {
					callbackName = request.getParameter(obj);
					break;
				}
			}
		}
		String jsonpValue = writeValueAsJSONP(callbackName, jsonValue);
		response.getOutputStream().print(jsonpValue);
	}
}
